package com.test.udp.thread;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * 接收端
 *
 * @create: 2019-05-28 22:45
 **/
public class TalkReceive implements Runnable {

    private DatagramSocket server;
    private String from;

    public TalkReceive(int port, String from) {
        this.from = from;
        try {
            server = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {

            //循环不停接收
            while (true) {

                //2.准备容器 封装成DatagramPacket包裹,创建一个字节数组对象,长度为UDP的最大长度1024*60
                byte[] data = new byte[1024 * 60];
                DatagramPacket packet = new DatagramPacket(data, 0, data.length);
                //3.阻塞式接收包裹receive(DatagramPacket p)
                server.receive(packet); //阻塞式
                //4.分析数据
                //byte[] getByte()
                //getLength()
                byte[] bytes = packet.getData();
                int l = bytes.length;
                //注意控制台输入时前后会有空格
                String datas = new String(bytes, 0, l).trim();
                System.out.println(from + ": " + datas);

                //跳出循环
                if (datas.equals("bye")) {
                    break;
                }
            }

            //5.释放资源
            server.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
